import { createRouter, createWebHistory } from 'vue-router'
import { useStore } from '@/store'
import defaultRoute from './defaultRoute'
import {transformAsyncMenus} from '@/util/common'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    ...defaultRoute
  ],
})

router.addRoute({
  path: '/:pathMatch(.*)*',
  name: 'NotFound',
  component: () => import('@/views/Error/index.vue')
})

let flag = true // 解决动态路由刷新消失的问题
router.beforeEach((to, from, next) => {
  // 获取token
  const { userStore, menuStore } = useStore()

  if (to.path === '/login') {
    next()
  } else {
    menuStore.setActiveName(to.name as string)
    menuStore.setBreadCrumb(to,router.getRoutes())
    if (userStore.token) {

      if(flag) {
        router.addRoute({
          path: '/',
          component: () => import('@/layout/Main.vue'),
          children: transformAsyncMenus(menuStore.menuList)
        })
        next({ path: to.fullPath })
      }else{
        next()
      }

    } else {
      next('/login')
    }
  }

  flag = false
})

export default router
